package com.forage.exp.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;

/**
 * 小程序工具类
 * @author : Ice'Clean
 * @date : 2022-05-02
 */
public class AppletUtils {

    /** 小程序 appId */
    private static final String APPID = "wx4136a1633c16e913";

    /** 小程序 appSecret */
    private static final String SECRET = "07e8bf0a57fb67e3a06f7e779a63cf9e";

    /** 获取 openId  */
    public static String getOpenId(String code){
        // 封装请求
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + APPID + "&secret=" + SECRET +
                "&js_code=" + code + "&grant_type=authorization_code";
        String response = restTemplate.getForObject(url, String.class);
        // 解析出 openId 并返回
        Object openId = JSONObject.parseObject(response).get("openid");
        return openId != null ? openId.toString() : null;
    }
}
